//
//  WBStatusPictureView.swift
//  Weibo
//
//  Created by cc on 10/21/17.
//  Copyright © 2017 cc. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {

    
    var viewModel: WBStatusViewModel? {
        didSet {
            calcViewSize()
            
            //設置urls
            urls = viewModel?.picUrls
            
        }
    }
    
    
    /// 根據視圖模型的配圖視圖大小， 調整顯示內容
    private func calcViewSize () {
        
        //處理寬度
        if viewModel?.picUrls?.count == 1 {
            
            //1>單圖，根據配圖視圖的大小，修改subviews[0]的寬高
            let viewSize = viewModel?.pictureViewSize ?? CGSize()
            
            // a) 獲取第0個圖像視圖
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: viewSize.width, height: viewSize.height - WBStatusPictureViewOutterMargin)
        } else {
           //2> 多圖(無圖)， 恢復subviews[0]的寬高，保證九宮格佈局的完整
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        }
        
        
        
        
        //修改調度約束
        heightCons.constant = viewModel?.pictureViewSize.height ?? 0
    }
    
    
    /// 配圖視圖數組
    private var urls: [WBStatusPicture]? {
        didSet{
            //1.隱藏所有的imageView
            for v in subviews {
                v.isHidden = true
            }
            
            //2.遍歷urls 數組，順序設置圖像
            var index = 0
            for url in urls ?? [] {
                //獲得對應索引的 imageView
                let iv = subviews[index] as! UIImageView
             
                
                //4張圖像處理
                if index == 1 && urls?.count == 4 {
                    index += 1
                }
                
                //設置圖像
                iv.cz_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                
                //判断是不是gif， 根据扩展名
                iv.subviews[0].isHidden = (((url.thumbnail_pic ?? "") as NSString).pathExtension.lowercased() != "gif")
                
                
                
                // 顯示圖像
                iv.isHidden = false
                index += 1
            }
        }
    }
    
    @IBOutlet weak var heightCons: NSLayoutConstraint!
    
    override func awakeFromNib() {
        setupUI()
    }
    
    
    //MARK: -监听方法
    @objc private func tapImageView(tap: UITapGestureRecognizer) {
        guard let iv = tap.view, let picURLs = viewModel?.picUrls else {
            return
        }
        
        var selectedIndex = iv.tag
        let urls = (picURLs as NSArray).value(forKey: "largePic") as! [String]
        
        //针对4张图处理
        if picURLs.count == 4 && selectedIndex > 1 {
            selectedIndex -= 1
        }
        
        //处理可见的图像数组
        var imageViewList = [UIImageView]()
        
        for iv in subviews as! [UIImageView] {
            if !iv.isHidden {
                imageViewList.append(iv)
            }
        }
        
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBStatusCellBrowserPhotoNotification), object: self, userInfo: [WBStatusCellBrowserPhotoURLsKey: urls, WBStatusCellBrowserPhotoSelectedIndexKey: selectedIndex, WBStatusCellBrowserPhotoImageViewsKey: imageViewList])
        
    }
    
}


// MARK: - 設置界面
extension WBStatusPictureView {
    //1. Cell中所有的控件都是提前設置好的
    //2. 設置的時候，根據數據決定是否顯示
    //3. 不要動態創建
    private func setupUI() {
        
        //設置背景顏色
        backgroundColor = superview?.backgroundColor
        
        //超出邊界的內容不顯示
        clipsToBounds = true
        
        
        let count = 3
        let rect = CGRect(x: 0, y: WBStatusPictureViewOutterMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        
        
        for i in 0..<count * count {
            let iv = UIImageView()
            
            // 設置 contentMode
            iv.contentMode = .scaleAspectFill
            iv.clipsToBounds = true
            
            //行
            let row = CGFloat(i / count)
            //列
            let col = CGFloat(i % count)
            let xOffset = col * (WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin)
            let yOffset = row * (WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin)
            iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
            
            addSubview(iv)
            
            
            //让imageView能够接收用户交互
            iv.isUserInteractionEnabled = true
            //添加手势识别
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapImageView))
            
            iv.addGestureRecognizer(tap)
            
            //设置imageView的tag
            iv.tag = i
            
            addGifView(iv: iv)
        }
    }
    
    //向图像视图添加gif提示图像
    private func addGifView (iv: UIImageView) {
        let gifImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        
        iv.addSubview(gifImageView)
        
        //自动布局
        gifImageView.translatesAutoresizingMaskIntoConstraints = false
        
        iv.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .right, relatedBy: .equal, toItem: iv, attribute: .right, multiplier: 1.0, constant: 0))
        
        iv.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .bottom, relatedBy: .equal, toItem: iv, attribute: .bottom, multiplier: 1.0, constant: 0))
        
    }
}
